###########################
## Visualizing results of 
## Two-way BART partial
## dependency
###########################

## Get processed data
load("./FullData.RData")
train.data  <- all.data$fData[,-grep("uid|train|fraud",colnames(all.data$fData))]   

## Generate data that can be used by lattice
topo.vals  <- c(t(laply(bartInterPlots,function(x)aaply(x$fd,2,median))))
topo.vals  <- as.data.frame(topo.vals)
names(topo.vals)  <- "Median"
xy.topo.vals <- ldply(bartInterPlots,function(x)(expand.grid(x$levs[[1]],x$levs[[2]])))
topo.vals$Predictor1 <- xy.topo.vals[,1]
topo.vals$Predictor2 <- xy.topo.vals[,2]
xy.topo.names  <- ldply(bartInterPlots,function(x){
  rename.fun  <- function(y){
    switch(y
           ,"instability.0"="Regime Stability"
           ,"DistanceLastPair"="Distance of last pair of digits"
           ,"Uniform.LastDigit"="Uniform Last Digit"
           ,"inequality.(43,60.1]"="Highest Inequality"
           ,"urban"="Urban"
           ,"turnout"="Turnout"
           ,"fract"="Ethnolinguistic fract."
    )
  }
  ntimes  <- nrow(expand.grid(x$levs[[1]],x$levs[[2]]))
  array(rep(laply(x$xlbs,rename.fun),each=ntimes),c(ntimes,2))
})
topo.vals$PredictorName1 <- xy.topo.names[,1]
topo.vals$PredictorName2 <- xy.topo.names[,2]

## Obtain values discussed in main text
subset(topo.vals, PredictorName1=="Turnout"&PredictorName2=="Distance of last pair of digits"&Predictor1<10)
subset(topo.vals, PredictorName1=="Turnout"&PredictorName2=="Distance of last pair of digits"&Predictor1>60&Predictor1<70)
subset(topo.vals, PredictorName1=="Turnout"&PredictorName2=="Distance of last pair of digits"&Predictor1>90)

## Produce graph using lattice
mytheme <- standard.theme("pdf", color=FALSE)
mytheme$axis.line$col <- "transparent"
one <- wireframe(Median~Predictor1*Predictor2,
                 data=subset(topo.vals, PredictorName1=="Turnout"&PredictorName2=="Distance of last pair of digits"),
                 drape=TRUE,
                 zoom=0.95,
                 par.settings=mytheme,
                 axis.line=list(col="transparent"),
                 screen=list(z=-20, x=-50, y=0),
                 light.source=c(10,10,10),
                 scales = list(arrows=FALSE, col = "black", font = 3),
                 colorkey=FALSE,
                 axes=FALSE,
                 xlab=list(label="Turnout", cex=1, rot =-17),
                 ylab=list(label="Distance of last pair\n of digits", cex=1, rot=70),
                 zlab=list(label = "Fraud", font = 1, cex = 1,rot=98),
                 ,strip = function(..., bg,par.strip.text){
                   strip.default(..., bg="gray80"
                                 ,par.strip.text=list(alpha=1 ,cex=.8 ,col="black"
                                                      ,font=1 ))} )
postscript("./InteractionPlot.ps", width=8, height=8)
one
dev.off()




